/**
 * 用户管理模块
 */
const router = require('koa-router')();
const jwt = require('../utils/jwt');
const util = require('../utils/util');
const leaveDB = require('../models/leaveSchema');
const deptDB = require('../models/deptSchema');

router.prefix('/leave');

// 分页 查询审批列表
router.get('/list', async (ctx) => {
  let { applyState, type } = ctx.request.query;
  // 获取token 信息
  let userInfo = util.getTokenInfo(ctx.request.headers.authorization);
  let { page, skipIndex } = util.pager(ctx.request.query);
  let params = {};
  if (type == 'approve') {
    // 这里是查询待我审批的列表
    if (applyState == 1 || applyState == 2) {
      params.curAuditUserName = userInfo.userName;
      params.$or = [{ applyState: 1 }, { applyState: 2 }];
    } else if (applyState > 2) {
      // 查询审批流中包含我
      params = { 'auditFlows.userId': userInfo.userId, applyState };
    } else {
      // 下面的写法是错误的
      // params.auditFlows = {};
      // params.auditFlows.userId = userInfo.userId;
      // 必须按照这种写法
      params = { 'auditFlows.userId': userInfo.userId };
    }
  } else {
    // 这里是查询我申请的列表
    if (applyState) params.applyState = applyState;
    params = { 'applyUser.userId': userInfo.userId };
  }
  try {
    let list = await leaveDB.find(params).skip(skipIndex).limit(page.pageSize);
    const total = await leaveDB.countDocuments(params);
    ctx.body = util.success({ list, page: { ...page, total } });
  } catch (error) {
    ctx.body = util.fail(`查询失败：${error.stack}`);
  }
});

// 提交申请
router.post('/add', async (ctx) => {
  let params = ctx.request.body;
  // 获取token 信息
  let userInfo = util.getTokenInfo(ctx.request.headers.authorization);
  // 生成单号
  params.orderNo = 'XiuJia' + util.formateDate(new Date(), 'yyyyMMddhhmmss');

  /*
    组装审批人，上级部门负责人，人事部门，财务部门负责人
  */
  let dept = await deptDB.findById(userInfo.deptId.pop());
  let userList = await deptDB.find({ deptName: { $in: ['人事部门', '财务部门'] } });
  params.curAuditUserName = dept.userName;
  params.auditUsers = dept.userName;
  /**
   * 组装审批流
   */
  params.auditFlows = [{ userId: dept.userId, userName: dept.userName, userEmail: dept.userEmail }];
  userList.map((item) => {
    params.auditFlows.push({ userId: item.userId, userName: item.userName, userEmail: item.userEmail });
    params.auditUsers += ',' + item.userName;
  });
  // 组装审批日志
  params.auditLogs = [];
  // 组装当前用户
  params.applyUser = { userId: userInfo.userId, userName: userInfo.userName, userEmail: userInfo.userEmail };

  try {
    await leaveDB.create(params);
    ctx.body = util.success({}, '创建成功');
  } catch (err) {
    ctx.body = util.fail(`请求失败：${error.stack}`);
  }
});

// 作废申请
router.post('/delete', async (ctx) => {
  let { _id } = ctx.request.body;
  try {
    await leaveDB.findByIdAndUpdate(_id, { applyState: 5, updateTime: new Date() });
    ctx.body = util.success({}, '申请已作废');
  } catch (err) {
    ctx.body = util.fail(`请求失败：${error.stack}`);
  }
});

// 审核通过
router.post('/pass', async (ctx) => {
  let { _id, remark } = ctx.request.body;
  // 获取token 信息
  let userInfo = util.getTokenInfo(ctx.request.headers.authorization);
  let params = {};
  //审批状态  1: '待审批', 2: '审批中', 3: '审批拒绝', 4: '审批通过', 5: '作废'
  // 审批日志添加信息
  let doc = await leaveDB.findById(_id);
  let auditLogs = doc.auditLogs || [];
  params.auditLogs = auditLogs;
  let auditFlows = doc.auditFlows || [];
  if (auditLogs.length === auditFlows.length) {
    // 审核流需要和审核人一一对应
    ctx.body = util.success({}, '申请单已处理，请勿重复提交');
  } else if (auditLogs.length + 1 === auditFlows.length) {
    // 到了最后一级了  审批通过
    params.applyState = 4;
  } else {
    // 其他情况  审批人修改成下一级
    params.applyState = 2;
    params.curAuditUserName = auditFlows[auditLogs.length + 1].userName;
  }
  params.auditLogs.push({ remark, userId: userInfo.userId, userName: userInfo.userName, createTime: new Date(), action: '审核通过' });
  try {
    await leaveDB.findByIdAndUpdate(_id, { ...params, updateTime: new Date() });
    ctx.body = util.success({}, '申请已通过');
  } catch (err) {
    ctx.body = util.fail(`请求失败：${error.stack}`);
  }
});

// 审核拒绝
router.post('/refuse', async (ctx) => {
  let { _id, remark } = ctx.request.body;
  // 获取token 信息
  let userInfo = util.getTokenInfo(ctx.request.headers.authorization);
  let params = {};
  //审批状态  1: '待审批', 2: '审批中', 3: '审批拒绝', 4: '审批通过', 5: '作废'
  params.applyState = 3;
  // 审批日志添加信息
  let doc = await leaveDB.findById(_id);
  params.auditLogs = doc.auditLogs || [];
  params.auditLogs.push({ remark, userId: userInfo.userId, userName: userInfo.userName, createTime: new Date(), action: '审核拒绝' });

  try {
    await leaveDB.findByIdAndUpdate(_id, { ...params, updateTime: new Date() });
    ctx.body = util.success({}, '申请已驳回');
  } catch (err) {
    ctx.body = util.fail(`请求失败：${error.stack}`);
  }
});

// 通知数量
router.get('/count', async (ctx) => {
  // 获取token 信息
  let userInfo = util.getTokenInfo(ctx.request.headers.authorization);
  let params = {};
  params.curAuditUserName = userInfo.userName;
  params.$or = [{ applyState: 1 }, { applyState: 2 }];

  try {
    let total = await leaveDB.countDocuments(params);
    ctx.body = util.success(total, '查询成功');
  } catch (err) {
    ctx.body = util.fail(`请求失败：${error.stack}`);
  }
});

module.exports = router;
